package com.zheng.blog.service.imp;

import com.zheng.blog.pojo.Article;
import com.zheng.blog.repository.ArticleRepository;
import com.zheng.blog.service.ArticleService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jackson.JsonObjectSerializer;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.*;

/**
 *  @author: zheng
 *  @Date: 2020-06-17 01:02
 *  @Description:基于reds文章分页查询展示
 */
@Service
public class ArticleServiceImp implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Map  selectArticleList(Integer current) {
        Integer score=0;
        if(current!=1){
            score=current+1;
        }else{
            score=current;
        }
        Map map=new HashMap();
        //根据redis的score进行分页,现在为1页2条数据，则查询redis中zset结构中的score,score为文章id
        //比如查询第1页，则查询score为1-2的数据，查询第2页，则查询score为3-4的数据
        Set<Article> set= redisTemplate.opsForZSet().rangeByScore("article",score,score+1);
        //查询redis中是否有分页的数据,如果有则直接从redis中取出
        if(set!=null&&set.size()!=0){
            List<Article> list=new ArrayList<>();
              for(Article sr:set){
                  list.add(sr);
              }
              map.put("list",list);
              map.put("total",redisTemplate.opsForValue().get("total"));
              return map;
        }else {
            //用jpa进行分页查询，page下标是从0开始的,而页数从1开始，所以减去1
            Pageable pageable= PageRequest.of(current-1,2);
            Page<Article> page= articleRepository.findAll(pageable);
            map.put("list",page.getContent());
            map.put("total",page.getPageable().getPageSize());
            //查询处数据根据id为score存储到redis中zset结构
            for(Article article:page){
                redisTemplate.opsForZSet().add("article",article,article.getId());
            }
            //存储有几页
            redisTemplate.opsForValue().set("total",page.getPageable().getPageSize());
            return map;

        }

    }
}
